package cn.com.wxd.service.keyword;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.common.file.ReadConfigFile;

/**
 * Title:关键字过滤
 * Description:cn.com.wxd.service.keywordfilter
 * <p>
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created time: 2016-6-21 下午1:18:49
 *
 * @author WangXuDong
 * @version 1.0
 */
public class KeyWordFilter {
    private static final Logger log = LoggerFactory.getLogger(KeyWordFilter.class);
    private static Pattern pattern = null;
    private static StringBuffer patternBuffer;

    static {
        try {
            initPattern();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 重新初始化关键字过滤服务
     *
     * @throws IOException
     */
    private static void initPattern() throws IOException {
        patternBuffer = new StringBuffer("(");
        try {

            InputStream in = KeyWordFilter.class.getResourceAsStream("filterwords.default.bin");
            Properties property = new Properties();
            property.load(in);
            Enumeration enu = property.propertyNames();
            int i = 0;
            while (enu.hasMoreElements()) {
                String scontent = ((String) enu.nextElement()).trim();
                if (!scontent.equals("")) {
                    patternBuffer.append(scontent + "|");
                    i++;
                }
            }
            log.debug("从默认词库增加了" + i + "个词！");
            log.debug("开始补充filterwords中的，的过滤词！");
            List<String> workStrs = ReadConfigFile.readCharFilebyLine(KeyWordFilter.class.getClassLoader()
                    .getResource("").getPath() + "filterwords.bin");
            if (workStrs != null && workStrs.size() > 0) {
                log.debug("获取到" + workStrs.size() + "个词");
                for (String workStr : workStrs) {
                    String scontent = workStr.trim();
                    if (!scontent.equals("")) {
                        patternBuffer.append(scontent + "|");
                    }
                }
            } else {
                log.warn("没有屏蔽词库filterwords.bin (encode=utf-8)，现使用默认的屏蔽词库！");
            }
        } catch (Exception e) {
            log.error("屏蔽词库初始化失败" + e);
        } finally {
            patternBuffer.append(")");
        }
        if (patternBuffer.length() >= 3) {
            patternBuffer.deleteCharAt(patternBuffer.length() - 1);
            patternBuffer.append(")");
            // 装换编码
            pattern = Pattern.compile(patternBuffer.toString());
        }
    }

    public static void addFileterWord(String word) {
        patternBuffer.replace(patternBuffer.length()-2,patternBuffer.length(),"|"+word+")");
        // 装换编码
        pattern = Pattern.compile(patternBuffer.toString());
    }

    /**
     * 关键字过滤，如果关键字库没有设置或发生错误，将不过滤
     *
     * @param str 过滤的文本
     *
     * @return 过滤后的文本
     */
    public static String doFilter(String str) {
        if (str == null || str.isEmpty()) {
            return "";
        }
        if (pattern == null) {
            try {
                initPattern();
            } catch (IOException e) {
                log.error("关键字过滤服务无法运行!", e);
                return str;
            }
        }
        if (pattern == null) {
            return str;
        }
        Matcher m = pattern.matcher(str);
        // 选择替换方式，这里以* 号代替
        str = m.replaceAll("*");
        return str;
    }
}
